package com.kaixuan.elasticsearch.util;

import com.kaixuan.elasticsearch.pojo.Goods;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @Copyright: Company.All rights reserved.
 * @Description:
 * @author: KaiXuan
 * @since: 2020/6/15 14:49
 * @history: 1.2020/6/15 created by KaiXuan
 */
@Component
public class JsoupUtil {

//    public static void main(String[] a)throws IOException {
//        new JsoupUtil().jingdong("java").forEach(System.out::println);
//    }
    public List<Goods> JDGoods(String keyWord) throws IOException {
        String url = "https://search.jd.com/Search?keyword=" + keyWord;
        Document parse = Jsoup.parse(new URL(url), 1000);
        Element j_crumbsBar = parse.getElementById("J_goodsList");
        Elements li = j_crumbsBar.getElementsByTag("li");
        List list = new ArrayList();
        Goods goods;
        for (Element element : li) {
            goods = new Goods();
            String img = element.getElementsByTag("img").get(0).attr("src");
            String p = element.getElementsByClass("p-price").get(0).text();
            String name = element.getElementsByClass("p-name").get(0).text();
            goods.setImg(img);
            goods.setPrice(p);
            goods.setTitle(name);
            list.add(goods);
        }
        return list;
    }
}
